package main

import (
	"context"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"github.com/xkgo/lcs/server"
)

func main() {
	// 创建长连接服务器
	wsServer := server.NewServer()

	// 创建HTTP服务器
	httpServer := &http.Server{
		Addr:    ":8080",
		Handler: wsServer,
	}

	// 捕获系统信号，优雅关闭
	stop := make(chan os.Signal, 1)
	signal.Notify(stop, os.Interrupt, syscall.SIGTERM)

	// 启动HTTP服务器
	go func() {
		log.Printf("Starting WebSocket server on %s", httpServer.Addr)
		if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Fatalf("Error starting server: %v", err)
		}
	}()

	// 等待中断信号
	<-stop
	log.Println("Shutting down server...")

	// 创建一个5秒的上下文用于优雅关闭
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	// 优雅关闭HTTP服务器
	if err := httpServer.Shutdown(ctx); err != nil {
		log.Fatalf("Server forced to shutdown: %v", err)
	}

	log.Println("Server exiting")
}
